package com.rocching.easychat.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rocching.easychat.R;
import com.rocching.easychat.adapter.SearchFriendListAdapter;
import com.rocching.easychat.core.IApiCallback;
import com.rocching.easychat.core.SimpleInputDialog;
import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.core.ViewClickListener;
import com.rocching.easychat.model.ResponseModel;
import com.rocching.easychat.model.SearchUserModel;
import com.rocching.easychat.service.FriendService;
import com.rocching.easychat.service.dto.AddFriendInput;
import com.rocching.easychat.util.JsonUtil;
import com.rocching.easychat.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class AddFriendActivity extends AppCompatActivity {
    private final String TAG = AddFriendActivity.class.getName();

    private SearchFriendListAdapter friendListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);

        init();
    }

    private void init() {
        EditText userName = findViewById(R.id.user_name);
        TextView search = findViewById(R.id.tv_search);

        search.setOnClickListener(new ViewClickListener() {
            @Override
            public void onDClick(View v) {
                hideKeyboard(v.getWindowToken());

                searchUsers(userName.getText().toString());
            }
        });

        initListView();
    }

    private void initListView() {
        ListView listView = findViewById(R.id.friend_list);
        friendListAdapter = new SearchFriendListAdapter(this);
        listView.setAdapter(friendListAdapter);

        listView.setOnItemClickListener(new ViewClickListener() {
            @Override
            public void onDItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SearchUserModel model = (SearchUserModel) listView.getItemAtPosition(i);
                itemClicked(model);
            }
        });
    }

    private void itemClicked(SearchUserModel model) {
        if (model.getId() == UserIdentityContext.getUserId()) {
            showText(getString(R.string.add_self_tip));
            return;
        }

        Integer status = model.getStatus();
        if (Objects.isNull(status)) {
            status = 0;
        }

        boolean canRequest = status == -1 || status == 1;
        if (!canRequest) {
            String errorMsg = String.format(getString(R.string.add_friend_status_tip), model.getStatusName());
            showText(errorMsg);
            return;
        }

        SimpleInputDialog dialog = new SimpleInputDialog();
        dialog.setInputHint(getString(R.string.friend_request_tip));
        dialog.setInputDialogListener(new SimpleInputDialog.InputDialogListener() {
            @Override
            public boolean onConfirmClicked(EditText editText) {
                String text = editText.getText().toString();
                if (StringUtil.isEmpty(text)) {
                    text = String.format(getString(R.string.me_tip), UserIdentityContext.getUserName());
                }

                addFriend(model.getId(), text);
                showText(getString(R.string.send_friend_request_tip));
                return true;
            }
        });
        dialog.show(getSupportFragmentManager(), null);
    }

    private void addFriend(long friendId, String greetMsg) {
        AddFriendInput input = new AddFriendInput();
        input.setFriendId(friendId);
        input.setGreetMsg(greetMsg);
        FriendService.getInstance().addFriend(input, new IApiCallback<ResponseModel>() {
            @Override
            public void onResponse(boolean succeeded, String body, ResponseModel data) {
                if (succeeded) {
                    Log.i(TAG, "the data is:" + JsonUtil.toJson(data));
                    showText(data.getMsg());
                    searchUsers();
                }
            }
        });
    }

    private void searchUsers() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EditText userName = findViewById(R.id.user_name);
                searchUsers(userName.getText().toString());
            }
        });
    }

    private void searchUsers(String keyword) {
        if (StringUtil.isEmpty(keyword)) {
            showText("请输入账号或名称");
            return;
        }

        FriendService.getInstance().searchFriend(keyword, new IApiCallback<Object>() {
            @Override
            public void onResponse(boolean succeeded, String body, Object data) {
                if (succeeded) {
                    try {
                        List<SearchUserModel> list = getUserList(body);
                        if (StringUtil.isEmpty(list)) {
                            updateView(new ArrayList<>());
                            showText("没有找到任何好友!");
                        } else {
                            updateView(list);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                } else {
                    showText("服务器出错,无法搜索好友!");
                }
            }
        });
    }

    private void updateView(List<SearchUserModel> list) {
        if (friendListAdapter != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    friendListAdapter.update(list);
                }
            });
        }
    }

    private List<SearchUserModel> getUserList(String json) {
        if (StringUtil.isEmpty(json)) {
            return null;
        }
        JSONObject jsonObject = JsonUtil.parseObject(json);
        if (jsonObject != null) {
            List<SearchUserModel> list = new ArrayList<>();
            JSONArray array = jsonObject.getJSONArray("Data");
            for (int i = 0; i < array.size(); i++) {
                list.add(array.getObject(i, SearchUserModel.class));
            }
            return list;
        }
        return null;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void showText(String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
        });
    }
}